package com.shengsiyuan.nio;

import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NioTest03 {

    public static void main(String[] arg) throws Exception {

        FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\Administrator\\IdeaProjects\\Netty-Learning\\src\\main\\java\\com\\shengsiyuan\\nio\\text\\Niotest3.txt");
        FileChannel fileChannel = fileOutputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(512);

        System.out.println("initialize :" + byteBuffer.capacity() + "," + byteBuffer.limit() + "," + byteBuffer.position());

        byte[] byteary = "hello world \n  my name is chovy , nice to meet you".getBytes();
        for (byte b : byteary) {
            byteBuffer.put(b);
        }
        System.out.println("first read :" + byteBuffer.capacity() + "," + byteBuffer.limit() + "," + byteBuffer.position());

        byteBuffer.flip();
        System.out.println("first flip :" + byteBuffer.capacity() + "," + byteBuffer.limit() + "," + byteBuffer.position());

        fileChannel.write(byteBuffer);
        System.out.println("first write:" + byteBuffer.capacity() + "," + byteBuffer.limit() + "," + byteBuffer.position());

        byteBuffer.flip();
        System.out.println("second flip:" + byteBuffer.capacity() + "," + byteBuffer.limit() + "," + byteBuffer.position());

        byte[] byteary2 = "hello world \n  my name is chovy".getBytes();
        for (byte b : byteary2) {
            byteBuffer.put(b);
        }
        System.out.println("second read:" + byteBuffer.capacity() + "," + byteBuffer.limit() + "," + byteBuffer.position());

        byteBuffer.rewind();
        System.out.println(" rewind:" + byteBuffer.capacity() + "," + byteBuffer.limit() + "," + byteBuffer.position());

        byteBuffer.put("sd".getBytes());
        System.out.println(" rewind put:" + byteBuffer.capacity() + "," + byteBuffer.limit() + "," + byteBuffer.position());

        byteBuffer.flip();
        System.out.println("third flip:" + byteBuffer.capacity() + "," + byteBuffer.limit() + "," + byteBuffer.position());

        fileChannel.write(byteBuffer);

        fileOutputStream.close();
    }

}
